use diesel::{prelude::*, r2d2::{ConnectionManager, Pool, PooledConnection}};
use std::sync::OnceLock;


fn create_db_pool() -> Pool<ConnectionManager<SqliteConnection>> {
    let database_url = std::env::var("DATABASE_URL")
        .expect("DATABASE_URL must be set");

    // 创建连接管理器
    let manager = ConnectionManager::<SqliteConnection>::new(database_url);

    // 配置连接池参数
    Pool::builder()
        .max_size(15)          // 最大连接数
        .min_idle(Some(5))     // 最小空闲连接数
        .connection_timeout(std::time::Duration::from_secs(30)) // 连接超时时间
        .build(manager)
        .expect("Failed to create database pool")
}

static POOL: OnceLock<Pool<ConnectionManager<SqliteConnection>>> = OnceLock::new();

fn get_pool() -> &'static Pool<ConnectionManager<SqliteConnection>> {
    POOL.get_or_init(create_db_pool)
}

pub fn establish_connection() -> PooledConnection<ConnectionManager<SqliteConnection>> {
    get_pool().get().expect("Failed to get database connection from pool")
}